const { formatTime } = require('../../utils/util.js')
const { getApiUrl } = require('../../config/config.js')

Page({
  data: {
    post: null,
    loading: true,
    commentText: '',
    replyTo: null, // 记录当前回复的评论
    isAnonymous: false,
    isSubmitting: false,
    showActionSheet: false,
    selectedComment: null,
    userInfo: wx.getStorageSync('userInfo'),
    isAuthor: false,  // 是否是帖子作者
    commentFocus: false,  // 添加一个状态控制输入框聚焦
    showReportModal: false,
    reportReasons: ['垃圾广告', '涉黄涉暴', '政治敏感', '其他原因'],  // 添加举报原因选项
    selectedReason: '',
    reportDetail: '',
    canSendComment: false
  },

  onLoad(options) {
    const { id, post } = options
    if (post) {
      const postData = JSON.parse(decodeURIComponent(post))
      // 处理时间格式
      postData.createTime = this.formatTime(postData.createTime)
      // 处理图片列表
      const imageList = []
      for (let i = 1; i <= 9; i++) {
        const image = postData[`image${i}`]
        if (image) imageList.push(image)
      }
      postData.imageList = imageList
      
      this.setData({
        post: postData,
        loading: false
      })
    }
    
    if (id) {
      this.loadPostDetail(id)
    }

    // 检查是否是作者
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo && this.data.post) {
      this.setData({
        isAuthor: userInfo.id === this.data.post.authorId
      })
    }
  },

  // 加载帖子详情
  async loadPostDetail(id) {
    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: getApiUrl(`/post/query/${id}`),
          method: 'GET',
          header: {
            'token': wx.getStorageSync('token')
          },
          success: resolve,
          fail: reject
        })
      })

      if (res.data.code === 200) {
        const post = res.data.data
        // 处理图片列表
        const imageList = []
        for (let i = 1; i <= 9; i++) {
          const image = post[`image${i}`]
          if (image) imageList.push(image)
        }
        
        post.imageList = imageList
        post.createTime = this.formatTime(post.createTime)
        
        // 处理评论时间
        if (post.comments) {
          post.comments.forEach(comment => {
            comment.createTime = this.formatTime(comment.createTime)
            if (comment.replies) {
              comment.replies.forEach(reply => {
                reply.createTime = this.formatTime(reply.createTime)
              })
            }
          })
        }

        // 收藏数量
        post.collectCount = post.collectsCount || 0

        // 判断当前用户是否是帖子作者
        const userInfo = wx.getStorageSync('userInfo')
        const isAuthor = userInfo && userInfo.id === post.authorId
        
        // 从本地存储读取点赞和收藏状态
        if (userInfo) {
          // 点赞状态
          const likedPosts = wx.getStorageSync('likedPosts') || {}
          const likedPostIds = likedPosts[userInfo.id] || []
          post.isLiked = likedPostIds.indexOf(post.id) !== -1
          
          // 收藏状态
          const collectedPosts = wx.getStorageSync('collectedPosts') || {}
          const collectedPostIds = collectedPosts[userInfo.id] || []
          post.isCollected = collectedPostIds.indexOf(post.id) !== -1
        }

        this.setData({ 
          post,
          isAuthor
        })
      }
    } catch (error) {
      console.error('Load post detail failed:', error)
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 返回上一页
  onBack() {
    wx.navigateBack({
      delta: 1,
      fail: () => {
        // 如果返回失败（比如直接进入详情页），则跳转到首页
        wx.switchTab({
          url: '/pages/index/index'
        })
      }
    })
  },

  // 点赞功能
  async onTapLike() {
    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }

    const { post } = this.data
    const userId = userInfo.id
    
    // 获取本地存储的点赞记录
    let likedPosts = wx.getStorageSync('likedPosts') || {}
    if (!likedPosts[userId]) {
      likedPosts[userId] = []
    }
    
    // 检查是否已点赞
    const isLiked = post.isLiked
    
    // 更新本地存储
    if (isLiked) {
      // 取消点赞，从数组中移除
      likedPosts[userId] = likedPosts[userId].filter(postId => postId !== post.id)
    } else {
      // 点赞，添加到数组
      if (likedPosts[userId].indexOf(post.id) === -1) {
        likedPosts[userId].push(post.id)
      }
    }
    
    // 保存到本地存储
    wx.setStorageSync('likedPosts', likedPosts)
    
    // 乐观更新UI
    this.setData({
      'post.isLiked': !isLiked,
      'post.likesCount': isLiked 
        ? Math.max(0, post.likesCount - 1) 
        : (post.likesCount || 0) + 1
    })
    
    wx.showLoading({ title: '处理中...', mask: true })
    
    try {
      // 发送点赞请求
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: getApiUrl(`/post/like/${post.id}/${userId}`),
          method: 'POST',
          header: {
            'token': wx.getStorageSync('token')
          },
          success: resolve,
          fail: reject
        })
      })

      if (res.data.code === 200) {
        const { status, totalLikes } = res.data.data
        
        // 更新当前页面的点赞状态
        this.setData({
          'post.isLiked': status === 1,
          'post.likesCount': totalLikes
        })
        
        // 根据服务器返回的状态更新本地存储
        if (status === 1) {
          // 确保帖子ID在点赞列表中
          if (likedPosts[userId].indexOf(post.id) === -1) {
            likedPosts[userId].push(post.id)
          }
        } else {
          // 确保帖子ID不在点赞列表中
          likedPosts[userId] = likedPosts[userId].filter(postId => postId !== post.id)
        }
        
        // 再次保存到本地存储
        wx.setStorageSync('likedPosts', likedPosts)

        // 同时更新首页列表中的点赞状态
        const pages = getCurrentPages()
        const indexPage = pages.find(p => p.route === 'pages/index/index')
        if (indexPage) {
          const posts = indexPage.data.posts
          const postIndex = posts.findIndex(p => p.id === post.id)
          if (postIndex !== -1) {
            indexPage.setData({
              [`posts[${postIndex}].isLiked`]: status === 1,
              [`posts[${postIndex}].likesCount`]: totalLikes
            })
          }
        }

        wx.showToast({
          title: status === 1 ? '点赞成功' : '已取消点赞',
          icon: 'success'
        })
      } else {
        // 如果请求失败，回滚UI和本地存储
        if (isLiked) {
          // 恢复点赞
          if (likedPosts[userId].indexOf(post.id) === -1) {
            likedPosts[userId].push(post.id)
          }
        } else {
          // 恢复取消点赞
          likedPosts[userId] = likedPosts[userId].filter(postId => postId !== post.id)
        }
        wx.setStorageSync('likedPosts', likedPosts)
        
        this.setData({
          'post.isLiked': isLiked,
          'post.likesCount': post.likesCount + (isLiked ? 1 : -1)
        })
        
        wx.showToast({
          title: '操作失败，请重试',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('Like failed:', error)
      
      // 发生错误时回滚UI和本地存储
      if (isLiked) {
        // 恢复点赞
        if (likedPosts[userId].indexOf(post.id) === -1) {
          likedPosts[userId].push(post.id)
        }
      } else {
        // 恢复取消点赞
        likedPosts[userId] = likedPosts[userId].filter(postId => postId !== post.id)
      }
      wx.setStorageSync('likedPosts', likedPosts)
      
      this.setData({
        'post.isLiked': isLiked,
        'post.likesCount': post.likesCount + (isLiked ? 1 : -1)
      })
      
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 预览图片
  previewImage(e) {
    const { urls, current } = e.currentTarget.dataset
    wx.previewImage({
      urls,
      current
    })
  },

  // 格式化时间
  formatTime(timeStr) {
    if (!timeStr) return '';
    
    const date = new Date(timeStr);
    const now = new Date();
    const diff = now - date;
    
    // 小于1分钟
    if (diff < 60000) {
      return '刚刚';
    }
    // 小于1小时
    if (diff < 3600000) {
      return `${Math.floor(diff / 60000)}分钟前`;
    }
    // 小于24小时
    if (diff < 86400000) {
      return `${Math.floor(diff / 3600000)}小时前`;
    }
    // 小于30天
    if (diff < 2592000000) {
      return `${Math.floor(diff / 86400000)}天前`;
    }
    // 其他
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  },

  // 下拉刷新
  async onPullDownRefresh() {
    const { post } = this.data
    if (post) {
      await this.loadPostDetail(post.id)
    }
    wx.stopPullDownRefresh()
  },

  // 评论
  onTapComment() {
    // 聚焦评论输入框
    this.setData({
      commentFocus: true  // 添加一个状态控制输入框聚焦
    })
  },

  // 分享
  onTapShare() {
    wx.showToast({
      title: '分享功能开发中',
      icon: 'none'
    })
  },

  // 评论输入处理
  onCommentInput(e) {
    const text = e.detail.value
    this.setData({
      commentText: text
    })
  },

  // 输入框失焦时
  onInputBlur() {
    // 延迟清除回复状态，以免影响提交
    setTimeout(() => {
      if (!this.data.isSubmitting) {
        this.setData({ replyTo: null })
      }
    }, 100)
  },

  // 点击回复按钮
  onTapReply(e) {
    const comment = e.currentTarget.dataset.comment
    this.setData({ 
      replyTo: comment,
      commentText: ''
    })
  },

  // 切换匿名状态
  toggleAnonymous() {
    this.setData({
      isAnonymous: !this.data.isAnonymous
    })
  },

  // 提交评论
  async submitComment() {
    const { commentText, isAnonymous, replyTo, post, isSubmitting } = this.data
    
    // 如果正在提交或评论内容为空，则不处理
    if (isSubmitting || !commentText.trim()) return

    try {
      const userInfo = wx.getStorageSync('userInfo')
      if (!userInfo) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        })
        return
      }

      this.setData({ isSubmitting: true })
      
      // 构建评论数据
      const commentData = {
        postId: post.id,
        userId: userInfo.id,
        commentText: commentText.trim(),
        isAnonymity: isAnonymous ? 1 : 0
      }

      // 如果是回复评论，添加父评论ID
      if (replyTo) {
        commentData.parentCommentId = replyTo.id
      }

      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: getApiUrl('/post/comment'),
          // url: 'http://localhost:8090/post/comment',
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'token': wx.getStorageSync('token')
          },
          data: commentData,
          success: resolve,
          fail: reject
        })
      })

      if (res.data.code === 200) {
        // 评论成功后重新加载帖子详情
        await this.loadPostDetail(post.id)
        
        // 清空输入框和状态
        this.setData({
          commentText: '',
          replyTo: null,
          isAnonymous: false
        })

        wx.showToast({
          title: '评论成功',
          icon: 'success'
        })
      } else {
        throw new Error(res.data.message || '评论失败')
      }
    } catch (error) {
      console.error('Submit comment failed:', error)
      wx.showToast({
        title: error.message || '评论失败，请重试',
        icon: 'none'
      })
    } finally {
      this.setData({ isSubmitting: false })
    }
  },

  // 显示评论操作菜单
  showCommentActions(e) {
    const comment = e.currentTarget.dataset.comment
    this.setData({
      showActionSheet: true,
      selectedComment: comment
    })
  },

  // 隐藏评论操作菜单
  hideCommentActions() {
    this.setData({
      showActionSheet: false,
      selectedComment: null
    })
  },

  // 阻止冒泡
  stopPropagation() {
    return
  },

  // 删除评论
  async deleteComment() {
    const { selectedComment, isAuthor, userInfo } = this.data
    
    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }

    // 判断是否有权限删除评论
    if (!isAuthor && selectedComment.userId !== userInfo.id) {
      wx.showToast({
        title: '无权删除该评论',
        icon: 'none'
      })
      return
    }

    try {
      wx.showLoading({
        title: '删除中...',
        mask: true
      })

      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: getApiUrl(`/post/comment/${selectedComment.id}/${userInfo.id}`),
          // url: `http://localhost:8090/post/comment/${selectedComment.id}/${userInfo.id}`,
          method: 'DELETE',
          header: {
            'token': wx.getStorageSync('token'),
            'is-author': isAuthor ? '1' : '0'  // 添加标识是否是作者的header
          },
          success: resolve,
          fail: reject
        })
      })

      if (res.data.code === 200) {
        await this.loadPostDetail(this.data.post.id)
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        })
      } else {
        wx.showToast({
          title: res.data.message || '删除失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('Delete comment failed:', error)
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
      this.hideCommentActions()
    }
  },

  // 举报评论
  async reportComment() {
    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }
    wx.showToast({
      title: '举报成功',
      icon: 'success'
    })
    this.hideCommentActions()
  },

  // 添加收藏/取消收藏方法
  async onTapCollect() {
    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }

    const { post } = this.data
    const userId = userInfo.id
    
    // 获取本地存储的收藏记录
    let collectedPosts = wx.getStorageSync('collectedPosts') || {}
    if (!collectedPosts[userId]) {
      collectedPosts[userId] = []
    }
    
    // 检查是否已收藏
    const isCollected = post.isCollected
    
    // 更新本地存储
    if (isCollected) {
      // 取消收藏，从数组中移除
      collectedPosts[userId] = collectedPosts[userId].filter(postId => postId !== post.id)
    } else {
      // 收藏，添加到数组
      if (collectedPosts[userId].indexOf(post.id) === -1) {
        collectedPosts[userId].push(post.id)
      }
    }
    
    // 保存到本地存储
    wx.setStorageSync('collectedPosts', collectedPosts)
    
    // 乐观更新UI
    this.setData({
      'post.isCollected': !isCollected,
      'post.collectCount': isCollected 
        ? Math.max(0, post.collectCount - 1) 
        : (post.collectCount || 0) + 1
    })
    
    wx.showLoading({ title: '处理中...', mask: true })
    
    try {
      // 发送收藏请求
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: getApiUrl(`/post/collect/${post.id}/${userId}`),
          method: 'POST',
          header: {
            'token': wx.getStorageSync('token')
          },
          success: resolve,
          fail: reject
        })
      })

      if (res.data.code === 200) {
        const { status, totalCollects } = res.data.data
        
        // 更新当前页面的收藏状态
        this.setData({
          'post.isCollected': status === 1,
          'post.collectCount': totalCollects
        })
        
        // 根据服务器返回的状态更新本地存储
        if (status === 1) {
          // 确保帖子ID在收藏列表中
          if (collectedPosts[userId].indexOf(post.id) === -1) {
            collectedPosts[userId].push(post.id)
          }
        } else {
          // 确保帖子ID不在收藏列表中
          collectedPosts[userId] = collectedPosts[userId].filter(postId => postId !== post.id)
        }
        
        // 再次保存到本地存储
        wx.setStorageSync('collectedPosts', collectedPosts)

        wx.showToast({
          title: status === 1 ? '收藏成功' : '已取消收藏',
          icon: 'success'
        })
      } else {
        // 如果请求失败，回滚UI和本地存储
        if (isCollected) {
          // 恢复收藏
          if (collectedPosts[userId].indexOf(post.id) === -1) {
            collectedPosts[userId].push(post.id)
          }
        } else {
          // 恢复取消收藏
          collectedPosts[userId] = collectedPosts[userId].filter(postId => postId !== post.id)
        }
        wx.setStorageSync('collectedPosts', collectedPosts)
        
        this.setData({
          'post.isCollected': isCollected,
          'post.collectCount': post.collectCount + (isCollected ? 1 : -1)
        })
        
        wx.showToast({
          title: '操作失败，请重试',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('Collect failed:', error)
      
      // 发生错误时回滚UI和本地存储
      if (isCollected) {
        // 恢复收藏
        if (collectedPosts[userId].indexOf(post.id) === -1) {
          collectedPosts[userId].push(post.id)
        }
      } else {
        // 恢复取消收藏
        collectedPosts[userId] = collectedPosts[userId].filter(postId => postId !== post.id)
      }
      wx.setStorageSync('collectedPosts', collectedPosts)
      
      this.setData({
        'post.isCollected': isCollected,
        'post.collectCount': post.collectCount + (isCollected ? 1 : -1)
      })
      
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 显示操作菜单
  showActionSheet() {
    this.setData({ showActionSheet: true })
  },

  // 隐藏操作菜单
  hideActionSheet() {
    this.setData({ showActionSheet: false })
  },

  // 删除帖子
  deletePost() {
    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo || !this.data.post) return

    wx.showModal({
      title: '确认删除',
      content: '确定要删除这篇帖子吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '删除中...' })
          
          wx.request({
            url: getApiUrl(`/post/${this.data.post.id}/${userInfo.id}`),
            method: 'DELETE',
            success: (res) => {
              if (res.data.code === 200) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success'
                })
                // 返回上一页并刷新列表
                const pages = getCurrentPages()
                const prevPage = pages[pages.length - 2]
                if (prevPage) {
                  prevPage.onPullDownRefresh()
                }
                setTimeout(() => {
                  wx.navigateBack()
                }, 1500)
              } else {
                wx.showToast({
                  title: '删除失败',
                  icon: 'none'
                })
              }
            },
            fail: () => {
              wx.showToast({
                title: '删除失败',
                icon: 'none'
              })
            },
            complete: () => {
              wx.hideLoading()
              this.hideActionSheet()
            }
          })
        }
      }
    })
  },

  // 显示举报弹窗
  onTapReport() {
    this.hideActionSheet() // 先隐藏操作菜单
    this.setData({
      showReportModal: true
    })
  },

  // 取消举报
  onCancelReport() {
    this.setData({
      showReportModal: false,
      reportDetail: '',
      selectedReason: ''
    })
  },

  // 选择举报原因
  onReportReasonChange(e) {
    this.setData({
      selectedReason: e.detail.value
    })
  },

  // 输入举报详情
  onReportDetailInput(e) {
    this.setData({
      reportDetail: e.detail.value
    })
  },

// 确认举报
async onConfirmReport() {
  const userInfo = wx.getStorageSync('userInfo')
  if (!userInfo) {
    wx.showToast({
      title: '请先登录',
      icon: 'none'
    })
    return
  }

  if (!this.data.selectedReason) {
    wx.showToast({
      title: '请选择举报原因',
      icon: 'none'
    })
    return
  }

  try {
    wx.showLoading({
      title: '提交中...',
      mask: true
    })

    // 构建举报内容
    let reason = this.data.selectedReason
    if (this.data.reportDetail) {
      reason += `：${this.data.reportDetail}`
    }

    const reportData = {
      postId: this.data.post.id,
      userId: userInfo.id,
      reason: reason
    }

    const res = await new Promise((resolve, reject) => {
      wx.request({
        url: getApiUrl('/post/report'),
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'token': wx.getStorageSync('token')
        },
        data: reportData,
        success: resolve,
        fail: reject
      })
    })

    if (res.data.code === 200) {
      wx.showToast({
        title: '举报成功',
        icon: 'success'
      })
      
      // 重置举报相关数据
      this.setData({
        showReportModal: false,
        reportDetail: '',
        selectedReason: ''
      })
    } else {
      throw new Error(res.data.message || '举报失败')
    }
  } catch (error) {
    console.error('Report failed:', error)
    wx.showToast({
      title: error.message || '举报失败，请重试',
      icon: 'none'
    })
  } finally {
    wx.hideLoading()
  }
},

  // 发送评论
  async onTapSend() {
    if (!this.data.canSendComment) {
      return
    }
    // ... 发送评论的逻辑
  }
})
